<?php

namespace Api\Controller;

/**
 * 积分兑换
 *
 * Class PointController
 * @package Api\Controller
 */
class PointController extends PublicController
{
    private $goods;
    private $category;

    public function _initialize()
    {
        parent::_initialize();
        $this->goods = M('goods');
        $this->category = M("category");
    }

    /**
     * 获取推荐商品
     */
    public function getRecommend()
    {
        $list = $this->goods->where('is_show = 1 and recommend = 1')->field('id, cover')->order('sort = 0, sort asc, id desc')->select();
        foreach ($list as $k => $v) {
            $list[$k]['cover'] = __DATAURL__ . $v['cover'];
        }

        $this->json_result($list);
    }

    /**
     * 积分商品列表
     */
    public function goodsList()
    {
        $where = "is_show = 1";
        $cate = I("get.cate");
        if ( empty($cate) ) {
            $category = $this->category->field('id')->order("id desc")->limit(1)->find();
            $where .=" AND cate_id=".$category['id'];
        } else {
            $where .=" AND cate_id=".$cate;
        }
        $perPage = !empty($_GET['per_page']) ? intval($_GET['per_page']) : 10;
        $curPage = !empty($_GET['page']) ? intval($_GET['page']) : 1;
        $count = $this->goods->where($where)->count();
        $totalPage = ceil($count / $perPage);
        $list = $this->goods->where($where)->field('id,name,cover,point,in_stock,sales_volume')->order('sort = 0, sort asc, id desc')->limit(($curPage - 1) * $perPage, $perPage)->select();
        foreach ($list as $k => $v) {
            $list[$k]['cover'] = __DATAURL__ . $v['cover'];
        }

        $this->json_result([
            'per_page'   => $perPage,
            'total'      => $count,
            'total_page' => $totalPage,
            'cur_page'   => $curPage,
            'list'       => $list,
        ]);
    }

    /**
     * 商品详情
     */
    public function detail()
    {
        $id = intval($_REQUEST['id']);
        $detail = $this->goods->where(['id' => $id])->find();
        if (!$detail) {
            $this->json_error('没有找到相关商品');
        }

        $goodsImages = M('goods_images')->where('goods_id = ' . $id)->order('sort asc')->select();
        $detail['images'] = [];
        foreach ($goodsImages as $value) {
            $detail['images'][] = __DATAURL__ . $value['image'];
        }

        $detail['content'] = str_replace(['../../../Data/', "/Data/"], ['/Data/', __DATAURL__], $detail['content']);
        $detail['cover'] = __DATAURL__ . $detail['cover'];

        $this->json_result($detail);
    }

    /**
     * 商品兑换  todo 事务
     */
    public function exchange()
    {
        $userId = intval($this->get("id"));
        if (!$userId) {
            $this->json_error("请登录");
        }

        if (empty($_POST['goods_id']) || empty($_POST['address_id'])) {
            $this->json_error('参数有误');
        }

        // 获取商品信息，库存及积分数
        $goodsInfo = M('goods')->where(['id' => intval($_POST['goods_id'])])->find();
        if (empty($goodsInfo) || !$goodsInfo['is_show'] || !$goodsInfo['in_stock']) {
            $this->json_error('商品不存在');
        }

        if (!$goodsInfo['in_stock']) {
            $this->json_error('商品库存不够');
        }

        // 获取用户积分
        $userPoint = M('user')->where('id = ' . $userId)->getField('point');
        if ($userPoint < $goodsInfo['point']) {
            $this->json_error('积分不够');
        }

        // 获取地址信息
        $address = M('address')->where('id = ' . intval($_POST['address_id']))->find();
        if (empty($address)) {
            $this->json_error('地址错误');
        }

        // 生成兑换订单
        $result = M('point_order')->add([
            'order_sn'  => date('YmdHis') . rand(10000, 999999),
            'goods_id'  => $goodsInfo['id'],
            'uid'       => $userId,
            'point'     => $goodsInfo['point'],
            'create_at' => date('Y-m-d H:i:s'),
            'status'    => 10,
            'receiver'  => $address['name'],
            'mobile'    => $address['mobile'],
            'address'   => $address['region_name'] . $address['address'],
        ]);

        //抵减积分
        M('user')->where('id = ' . $userId)->setDec('point', $goodsInfo['point']);


        // 积分记录
        M('point_log')->add([
            'user_id'   => $userId,
            'point'     => 0 - $goodsInfo['point'],
            'type'      => 1,
            'remark'    => '积分兑换商品 - ' . $goodsInfo['name'],
            'create_at' => date('Y-m-d H:i:s')
        ]);

        // 减少商品库存
        M('goods')->where(['id' => $goodsInfo['id']])->setDec('in_stock');

        if ($result) {
            $this->json_result([], '兑换成功');
        } else {
            $this->json_error('兑换失败');
        }
    }

    /**
     * 订单列表
     */
    public function orderList()
    {
        $userId = intval($this->get("id"));
        if (!$userId) {
            $this->json_error("请登录");
        }

        $perPage = !empty($_GET['per_page']) ? intval($_GET['per_page']) : 10;
        $curPage = !empty($_GET['page']) ? intval($_GET['page']) : 1;
        $status = !empty($_GET['status']) ? intval($_GET['status']) : 0;
        $where = "uid =" . $userId;
        $status && $where .= ' and status = ' . $status;

        $count = M('point_order')->join('lr_goods g on g.id = lr_point_order.goods_id')->where($where)->count();
        $totalPage = ceil($count / $perPage);
        $list = M('point_order')->where($where)->join('lr_goods g on g.id = lr_point_order.goods_id')
            ->field('g.name, g.cover, g.point, lr_point_order.id,lr_point_order.goods_id, lr_point_order.status')
            ->order('lr_point_order.id desc')->limit(($curPage - 1) * $perPage, $perPage)->select();
        foreach ($list as $k => $v) {
            $list[$k]['cover'] = __DATAURL__ . $v['cover'];
        }

        $this->json_result([
            'per_page'   => $perPage,
            'total'      => $count,
            'total_page' => $totalPage,
            'cur_page'   => $curPage,
            'list'       => $list,
        ]);
    }

    /**
     * 订单详情
     */
    public function order()
    {
        $userId = intval($this->get("id"));
        if (!$userId) {
            $this->json_error("请登录");
        }

        $orderId = intval($_GET['id']);
        if (empty($orderId)) {
            $this->json_error("参数错误");
        }

        $orderInfo = M('point_order')->where('uid = ' . $userId . ' and id = ' . $orderId)->find();
        if (empty($orderInfo)) {
            $this->json_error("订单信息错误");
        }
        $orderInfo['goods'] = M('goods')->where('id = ' . $orderInfo['goods_id'])->field('id, name, cover')->find();
        if (!empty($orderInfo['goods']['cover'])) {
            $orderInfo['goods']['cover'] = __DATAURL__ . $orderInfo['goods']['cover'];
        }

        $this->json_result($orderInfo);
    }

    /**
     * 订单确认收货
     */
    public function orderReceipt()
    {
        $userId = intval($this->get("id"));
        if (!$userId) {
            $this->json_error("请登录");
        }
        $orderId = intval($_GET['id']);
        if (empty($orderId)) {
            $this->json_error("参数错误");
        }
        $orderInfo = M('point_order')->where('uid = ' . $userId . ' and id = ' . $orderId)->find();
        if (empty($orderInfo) || $orderInfo['status'] != 20) {
            $this->json_error("订单信息错误");
        }
        $result = M('point_order')->where('id = ' . $orderId)->save(['status' => 30]);

        if ($result) {
            $this->json_result([], '操作成功');
        } else {
            $this->json_error('操作失败');
        }
    }
    
    /**
     * 获取分类名称
     */
    public function goodsCate()
    {
        $cate = $this->category->order('id desc')->select();
        $this->json_result(array('cate'=>$cate));
        
    }
}